﻿using Engine;
using Game;
using GameEntitySystem;
using Mekiasm.Interface;
using TemplatesDatabase;

namespace Mekiasm
{
    public class ComponentIronFurnace : ComponentEnergyMachine, IUpdateable
    {
        public int RemainResultCount = 0;
        public float CacheTemprature = 0;
        public int FuelValue = 0;
        public float Temprature = 0;
        public int MaxTemprature = 1000;
        public int MaxCacheFuel = 1000;
        public float MaxFactor = 1f;
        public UpdateOrder UpdateOrder => UpdateOrder.SubsystemPlayers;
        public override IDynamicCraft CraftDevice => MekCraftingRecipe.FindCraftDevice(typeof(IronFurnace));

        public void Update(float dt)
        {
            MaxFactor = GetSlotValue(5) == Bellows.Index ? 3f : 1f;
            float MaxT = MaxTemprature * MaxFactor;
            int value = GetSlotValue(2);
            Block block = BlocksManager.Blocks[Terrain.ExtractContents(value)];
            float fuelAmount = block.GetFuelFireDuration(value) * 100;
            int count = GetSlotCount(2);
            if (count > 0 && CacheTemprature + fuelAmount <= MaxCacheFuel && ILibrary.SubsystemTime.PeriodicGameTimeEvent(1.0, 0.0))
            {//处理燃料
                CacheTemprature += fuelAmount;
                RemoveSlotItems(2, 1);
            }
            if (ILibrary.SubsystemTime.PeriodicGameTimeEvent(0.1, 0.0))
            {
                if (CacheTemprature > 0)
                {//转换温度
                    if (Temprature < MaxT)
                    {
                        Temprature += 1f;
                        Temprature = MathUtils.Min(Temprature, MaxT);
                    }
                    CacheTemprature -= 1f;
                    CacheTemprature = MathUtils.Max(0, CacheTemprature);
                }
                else if (Temprature > 0 && CacheTemprature == 0)
                {//降温
                    Temprature -= 1f;
                    Temprature = MathUtils.Max(0, Temprature);
                }
            }

            HeatLevel = Temprature / 1000;

            MekRecipe.CircleCraft(this, HeatLevel);

        }
        public override void Load(ValuesDictionary valuesDictionary, IdToEntityMap idToEntityMap)
        {
            CacheTemprature = valuesDictionary.GetValue<float>("CT");
            Temprature = valuesDictionary.GetValue<float>("T");
            HeatLevel = Temprature / 1000;
            base.Load(valuesDictionary, idToEntityMap);
        }
        public override void Save(ValuesDictionary valuesDictionary, EntityToIdMap entityToIdMap)
        {
            valuesDictionary.SetValue("CT", CacheTemprature);
            valuesDictionary.SetValue("T", Temprature);
            base.Save(valuesDictionary, entityToIdMap);
        }
    }
}
